<template>
    <div class="chat-container">
      <header class="chat-header">
        <h1>智能问答助手</h1>
      </header>
      
      <div class="chat-messages" ref="messagesContainer">
        <div 
          v-for="(message, index) in messages" 
          :key="index" 
          :class="['message', message.role]"
        >
          <div class="message-avatar">
            <img v-if="message.role !== 'user'"
              :src="message.role === 'user' ? userAvatar : assistantAvatar" 
              :alt="message.role"
            />
          </div>
          <div class="message-content">
            <div class="message-text" v-html="formatMessage(message.content)"></div>
            <div class="message-time">{{ formatTime(message.timestamp) }}</div>
          </div>
          <div class="message-avatar-user">
            <img v-if="message.role === 'user'"
                :src="message.role === 'user' ? userAvatar : assistantAvatar" 
                :alt="message.role"
                />
            </div>
        </div>
        
        <div v-if="isLoading" class="message assistant">
          <div class="message-avatar">
            <img :src="assistantAvatar" alt="assistant" />
          </div>
          <div class="message-content">
            <div class="message-text typing">
              <span class="dot"></span>
              <span class="dot"></span>
              <span class="dot"></span>
            </div>
          </div>
        </div>
      </div>
      
      <div class="chat-input-area">
        <div class="input-container">
          <textarea
            v-model="userInput"
            @keydown.enter.exact.prevent="sendMessage"
            placeholder="输入您的问题..."
            rows="1"
            ref="textarea"
            @input="adjustTextareaHeight"
          ></textarea>
          <button @click="sendMessage" :disabled="!userInput.trim() || isLoading">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
              <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
            </svg>
          </button>
        </div>
        <div class="input-footer">
          <small>AI可能会犯错，请核实重要信息</small>
        </div>
      </div>
    </div>
  </template>
  
  <script>
  import { ref, computed, nextTick, onMounted, watch } from 'vue'
//   import {getMyUserInfo} from './hooks'
  import { deepseek } from "../../service/qAndA/index";
  import { useUserStore } from "../../store/user"

//   const { userInfo } = getMyUserInfo();
  export default {
    setup() {
      const userAvatar = ref('https://avatars.githubusercontent.com/u/1?v=4') // 默认用户头像
      const assistantAvatar = ref('https://avatars.githubusercontent.com/u/2?v=4') // 默认助手头像
      
      const userInput = ref('')
      const isLoading = ref(false)
      const messages = ref([])
      const messagesContainer = ref(null)
      const textarea = ref(null)
      const userInfo = ref()
    const getMyUserInfo = async() =>{
    const userStore = useUserStore()
    await userStore.getUserInfo()
    userInfo.value = computed(() => userStore.userInfo).value
    console.log(userInfo.value)

    // return userInfo.value.value
  }
      // 初始化一些示例对话
      onMounted(async() => {
        await getMyUserInfo()
        // userAvatar.value = userInfo
        userAvatar.value = 'https://api.touce.com.cn'+userInfo.value.avatar
        console.log(userInfo.value,'userAvatar.value')
        messages.value = [
          {
            role: 'assistant',
            content: '你好！我是智能助手，有什么可以帮您的吗？',
            timestamp: new Date()
          }
        ]
        
        // 自动聚焦输入框
        textarea.value.focus()
      })
      
      // 监听消息变化，自动滚动到底部
      watch(messages, () => {
        nextTick(() => {
          scrollToBottom()
        })
      }, { deep: true })
      
      // 格式化消息内容（简单的换行转换）
      const formatMessage = (text) => {
        // text?.replace(/\n/g, '<br>')
        return text
      }
      
      // 格式化时间显示
      const formatTime = (date) => {
        return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
      }
      
      // 调整文本框高度
      const adjustTextareaHeight = () => {
        const textareaEl = textarea.value
        textareaEl.style.height = 'auto'
        textareaEl.style.height = `${Math.min(textareaEl.scrollHeight, 150)}px`
      }
      
      // 滚动到底部
      const scrollToBottom = () => {
        if (messagesContainer.value) {
          messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
        }
      }
      
      // 发送消息
      const sendMessage = async () => {
        const inputText = userInput.value.trim()
        if (!inputText || isLoading.value) return
        console.log(inputText)
        // 添加用户消息
        const userMessage = {
          role: 'user',
          content: inputText,
          timestamp: new Date()
        }
        messages.value.push(userMessage)
        
        // 清空输入框
        userInput.value = ''
        textarea.value.style.height = 'auto'
        
        // 模拟AI思考
        isLoading.value = true
        
        try {
          // 这里应该是实际的API调用
          // const response = await fetchAIResponse(inputText)
          // 模拟API延迟
          await new Promise(resolve => setTimeout(resolve, 1500))
          
          // 模拟AI回复
          const aiResponse = {
            role: 'assistant',
            content: await getMockAIResponse(inputText),
            timestamp: new Date()
          }
          console.log(aiResponse,'aiResponse')
          messages.value.push(aiResponse)
        } catch (error) {
          console.error('获取AI回复失败:', error)
          messages.value.push({
            role: 'assistant',
            content: '抱歉，处理您的请求时出现了问题。请稍后再试。',
            timestamp: new Date()
          })
        } finally {
          isLoading.value = false
        }
      }
      
      // 模拟AI回复（实际应用中应该调用API）
      const getMockAIResponse = async (question) => {
        // const responses = [
        //   `关于"${question}"，这是一个很好的问题。根据我的理解...`,
        //   `"${question}"这个问题涉及到多个方面。首先...`,
        //   `感谢您的提问。"${question}"的答案可能因具体情况而异...`,
        //   `我理解您想了解"${question}"。以下是一些相关信息...`,
        //   `"${question}"是一个常见问题。简而言之...`
        // ]
      const responses = await deepseek({problem:question})
        // console.log('123',responses)
        // // 随机选择一个回复模板
        // let response = responses[Math.floor(Math.random() * responses.length)]
        
        // // 50%概率添加更多内容
        // if (Math.random() > 0.5) {
        //   response += "\n\n如果您需要更详细的信息，可以进一步说明您的具体需求。"
        // }
        
        // // 30%概率添加列表
        // if (Math.random() > 0.7) {
        //   response += "\n\n主要要点包括：\n- 第一点\n- 第二点\n- 第三点"
        // }
        return responses.msg
        // console.log(resolve(responses.msg))

      }
      
      return {
        userAvatar,
        assistantAvatar,
        userInput,
        isLoading,
        messages,
        messagesContainer,
        textarea,
        formatMessage,
        formatTime,
        adjustTextareaHeight,
        sendMessage
      }
    }
  }
  </script>
  
  <style scoped>
  .chat-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    max-width: 900px;
    margin: 0 auto;
    background-color: #f9f9f9;
    border-left: 1px solid #e0e0e0;
    border-right: 1px solid #e0e0e0;
  }
  
  .chat-header {
    padding: 15px 20px;
    border-bottom: 1px solid #e0e0e0;
    background-color: #fff;
    text-align: center;
  }
  
  .chat-header h1 {
    margin: 0;
    font-size: 1.5rem;
    color: #333;
  }
  
  .chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    background-color: #fff;
  }
  
  .message {
    display: flex;
    margin-bottom: 20px;
    animation: fadeIn 0.3s ease;
  }
  
  @keyframes fadeIn {
    from { opacity: 0; transform: translateY(10px); }
    to { opacity: 1; transform: translateY(0); }
  }
  
  .message-avatar {
    margin-right: 15px;
  }

  .message-avatar-user {
    margin-left: 15px;
  }
  
  .message-avatar img {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    object-fit: cover;
  }
.message-avatar-user img {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    object-fit: cover;
  }
  .message-content {
    flex: 1;
    max-width: calc(100% - 55px);
  }
  
  .message-text {
    padding: 12px 16px;
    border-radius: 18px;
    line-height: 1.5;
    word-wrap: break-word;
  }
  
  .user .message-text {
    background-color: #007bff;
    color: white;
    border-bottom-right-radius: 4px;
  }
  
  .assistant .message-text {
    background-color: #f0f0f0;
    color: #333;
    border-bottom-left-radius: 4px;
  }
  
  .message-time {
    font-size: 0.75rem;
    color: #999;
    margin-top: 5px;
    margin-left: 10px;
  }
  
  .typing {
    display: inline-flex;
    align-items: center;
    height: 20px;
  }
  
  .dot {
    width: 8px;
    height: 8px;
    margin: 0 2px;
    background-color: #999;
    border-radius: 50%;
    animation: bounce 1.4s infinite ease-in-out;
  }
  
  .dot:nth-child(1) {
    animation-delay: -0.32s;
  }
  
  .dot:nth-child(2) {
    animation-delay: -0.16s;
  }
  
  @keyframes bounce {
    0%, 80%, 100% { transform: scale(0); }
    40% { transform: scale(1); }
  }
  
  .chat-input-area {
    padding: 15px;
    background-color: #fff;
    border-top: 1px solid #e0e0e0;
  }
  
  .input-container {
    display: flex;
    align-items: flex-end;
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 8px;
    background-color: #fff;
  }
  
  textarea {
    flex: 1;
    border: none;
    resize: none;
    outline: none;
    font-family: inherit;
    font-size: 1rem;
    max-height: 150px;
    padding: 8px;
    line-height: 1.5;
  }
  
  button {
    background: none;
    border: none;
    cursor: pointer;
    padding: 8px;
    margin-left: 5px;
    color: #007bff;
    transition: color 0.2s;
  }
  
  button:disabled {
    color: #ccc;
    cursor: not-allowed;
  }
  
  button:hover:not(:disabled) {
    color: #0056b3;
  }
  
  button svg {
    width: 24px;
    height: 24px;
  }
  
  .input-footer {
    text-align: center;
    margin-top: 8px;
    color: #999;
    font-size: 0.8rem;
  }
  
  /* 响应式设计 */
  @media (max-width: 768px) {
    .chat-container {
      border: none;
    }
    
    .message-avatar img {
      width: 32px;
      height: 32px;
    }
    
    .message-content {
      max-width: calc(100% - 47px);
    }
  }
  </style>